<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>sliding block</title>
		<style>
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}

			.container {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 100vw;
				height: 100vh;
			}

			.box {
				height: 34px;
				padding: 4px;
				background-color: rgba(0, 0, 255, 0.5);
				border-radius: 6px;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				gap: 6px;
			}

			.item {
				height: 28px;
				border-radius: 4px;
				padding: 0 16px;
				line-height: 28px;
				color: white;
				cursor: pointer;
			}

			.active {
				background-color: #fff;
				color: #333;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<div class="box">
				<div data-item="1" class="item active">首页</div>
				<div data-item="1" class="item">Blog</div>
				<div data-item="1" class="item">关于我们</div>
				<div data-item="1" class="item">breeze</div>
			</div>
		</div>

		<script>
			const box = document.querySelector('.box');

			/**
			 * classList
			 * classList中包含length属性，可迭代
			 * add(value): 像类名列表中添加指定的值，如果已经存在，则什么也不做
			 * contains(value): 返回boolean，表示给定的value是否存在
			 * remove(value): 从类名列表中删除指定的value
			 * toggle(value): 如果类名列表中存在指定的value，则删除，如果不存在，则添加
			 */

			box.addEventListener('click', (event) => {
				const current = event.target;
				const attribute = current.getAttribute('data-item');
				if (attribute) {
					const items = document.querySelectorAll('.item');
					for (const el of items) {
						if (el.classList.contains('active')) {
							el.classList.remove('active');
						}
					}
					current.classList.add('active');
				}
			});
		</script>
	</body>
</html>
